var path = require('path');
var fs = require('fs');
var Consts = require('../../../util/consts')
var fileBasePath = '/home/work';
var uploadDir = path.join(fileBasePath, '/uploads/hideAndSeek');
module.exports = function (app) {
    return new FileHandler(app);
};


var FileHandler = function (app) {
    this.app = app;
};
var handler = FileHandler.prototype;

/**
 * 上传文件
 * @param msg {file: binaryString, filename: xxx}
 * @param session
 * @param next
 */
handler.upload = function (msg, session, next) {

    var filename = msg.filename;

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    filename = path.join(uploadDir, filename);

    fs.writeFile(filename, new Buffer(msg.file, 'base64'), function (err) {
        if (err) {
            console.log(err);
            next(null, {
                code: 'fail'
            });
            return;
        }
    });
    next(null, {
        code: 'success', url: msg.filename
    });
};

/**
 * 下载文件
 * @param msg {filename: xxx, username: xxx}
 * @param session
 * @param next
 */
handler.download = function (msg, session, next) {
    var filename = msg.filename;
    var username = msg.username;

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    filename = path.join(uploadDir, filename);
    fs.readFile(filename, 'base64', function (err, data) {
        console.log('download: ' + typeof data);
        if (err) {
            next(null, {
                code: 'fail'
            });
        } else {

            next(null, {
                code: 'success',
                file: data
            });
        }
    });
}